<template>
  <div class="user-regis-card-wrapper">
    <i class="back-to-login iconfont icon-arrow-left-bold"
    @click="$emit('toLog')"
    ></i>

		<i class="iconfont icon-cancel" @click="$emit('exit')"></i>

    <h2>注册</h2>

    <ul class="input-info-list">
      <li v-for="(item, idx) in infos" :key="idx">
        <component :is="(idx===2||idx===3)?'PasswordInput':'BaseInput'" 
				:placeholder="item.placeholder"
				:value="inputs[idx]"
				@change="renewInput($event.target, item.key)"
				class="info-input"/>
        <i class="iconfont icon-warning signal" v-show="ifError[idx].sign"></i>
        <p class="sig-message" v-show="ifError[idx].sign && ifError[idx].message">{{ifError[idx].message}}</p>
      </li>
    </ul>

		<div class="verification">
			<base-input
			class="veri-input"
			placeholder="请输入验证码"
			@change="renewInput($event.target, 'verification')"
			></base-input>
			<img src="" alt="" ref="veriImg" title="点击更换验证码"
			@click="loadVeriImg">
		</div>

    <button class="regis-button" @click="register" ref="registerBtn">Register</button>
  </div>
</template>

<script>
import BaseInput from '../utils/Input/BaseInput.vue';
import PasswordInput from '../utils/Input/PasswordInput.vue';

export default {
	components: {
		BaseInput,
		PasswordInput,
	},
	data() {
		return {
			inputs: {
				email: '',
				username: '',
				userpwd: '',
				userpwdConfirm: '',
				verification: ''
			},
			infos: [
				{
					key: 'email',
					placeholder: '请输入您的邮箱'
				},
				{
					key: 'username',
					placeholder: '请输入您的用户名'
				},
				{
					key: 'userpwd',
					placeholder: '请输入密码'
				},
				{
					key: 'userpwdConfirm',
					placeholder: '确认密码'
				},
			],
			ifError: Array.from(new Array(5), () => ({
				sign: false,
				message: ''
			})),
			ifShowPwd: false,
			ifShowPwdCon: false
		}
	},
	methods: {
		checkEmail(email) {
			if(!/^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/.test(email)) {
				this.ifError[0].sign = true;
				this.ifError[0].message = '邮箱格式不正确';
				return true;
			} else {
				this.$post({
					name: 'check email',
					url: 'register/check/email',
					data: {
						email
					}
				}).then(res => {
					this.ifError[0].sign = !res.data.success;
					this.ifError[0].message = res.data.message;
				});
			}
		},
		checkUsername(username) {
			if (username.length < 6 || username.length > 18) {
				this.ifError[1].sign = true;
				this.ifError[1].message = '用户名长度必须为6-18位';
				return true;
			} else if (/[^a-zA-Z0-9-_]/.test(username)) {
				this.ifError[1].sign = true;
				this.ifError[1].message = '用户名只能包含字母，数字，-(连字符)和_(下划线)';
				return true;
			} else {
				this.$post({
					name: 'check username',
					url: 'register/check/username',
					data: {
						username
					}
				}).then(res => {
					this.ifError[1].sign = !res.data.success;
					this.ifError[1].message = res.data.message;
				})
			}
		},
		checkPassword(password) {
			if(!(/[a-zA-Z]/.test(password) && /[0-9]/.test(password))) {
				this.ifError[2].sign = true;
				this.ifError[2].message = '密码至少包含一个字母，一个数字';
				return true;
			} else {
				this.ifError[2].sign = false;
				return false;
			}
		},
		checkPasswordConfirm(p1, p2) {
			if(p1 !== p2) {
				this.ifError[3].sign = this.ifError[2].sign = true;
				this.ifError[2].message = '';
				this.ifError[3].message = '两次输入密码不一致'
				return true;
			} else {
				this.ifError[3].sign = this.ifError[4].sign = false;
				return false;
			}
		},
		checkVerification(verification) {
			this.$post({
				name: 'check verification',
				url: 'register/verify/code',
				data: {
					user_input: verification
				}
			}).then(res => {
				if(res.data.success) this.ifError[4].sign = false;
				else {
					this.$alert({
						type: 'error',
						content: res.data.message
					});
					this.loadVeriImg();
				}
			});
			this.ifError[4].sign = false;
			return false;
		},
		renewInput(el, key){
			this.inputs[key] = el.value;
			console.log('register card inputs: ', this.inputs);
			this.checkFormat(key)
		},
		loadVeriImg() {
			this.$get({
				name: 'verification img',
				url: 'register/generate/code?random='+Math.random(),
				responseType: 'blob'
			}).then(res => {
				const reader = new FileReader();
				reader.onload = () => {
					this.$refs.veriImg.src = reader.result;
				}
				reader.readAsDataURL(res.data);
			}).catch(error => {
				this.$alert({
					type: 'error',
					content: '注册验证码获取失败'
				})
			});
		},	
		register() {
			if(this.ifError.filter(e => e.sign).length) {
				this.$alert({
          type: 'error',
          content: '请填写正确的注册信息'
        });
				return;
			}
			this.$store.commit('register', {
				infos: JSON.parse(JSON.stringify(this.inputs)),
				callback: (success) => {
					success && this.$emit('exit');
				}
			});
			this.$refs.registerBtn.disabled = true;
		},
		checkFormat(key) {
			switch(key) {
				case 'email':
					this.checkEmail(this.inputs.email);
					break;
				case 'username':
					this.checkUsername(this.inputs.username);
					break;
				case 'userpwd':
					!this.checkPasswordConfirm(this.inputs.userpwd, this.inputs.userpwdConfirm) && this.checkPassword(this.inputs.userpwd);
					break;
				case 'userpwdConfirm':
					!this.checkPasswordConfirm(this.inputs.userpwd, this.inputs.userpwdConfirm) && this.checkPassword(this.inputs.userpwd);
					break;
				case 'verification':
					this.checkVerification(this.inputs.verification);
					break;
			}
		}
	}
}
</script>

<style scoped lang="less">
@w: var(--userRegisCardWidth);
@fs: calc(var(--userRegisCardWidth) * 0.05);
@ifs: calc(@fs * 0.8);
@iw: calc(@w * 0.7);

.user-regis-card-wrapper {
	box-sizing: border-box;
  position: relative;
	width: @w;
	padding: calc(@w * 0.1) calc((@w - @iw) / 2);
	background-color: white;
	border-radius: calc(@w * 0.02);
	text-align: center;

	.icon-cancel {
		right: 0;

		&:hover {
			transform: rotate(180deg);
		}
	}

	.back-to-login {
		left: 0;

		&:hover {
			color: var(--darkBlue);
		}
	}

	.icon-cancel,
	.back-to-login {
		--a: 3vw;
		position: absolute;
		top: 0;
		display: block;
		width: var(--a);
		height: var(--a);
		line-height: var(--a);
		text-align: center;
		font-size: 1.2vw;
		font-weight: bold;
		color: var(--black);
		transition: .5s;

		&:hover {
			cursor: pointer;
		}
	}

	h2 {
		font-size: calc(@fs * 1.5);
		color: var(--blue);
		line-height: 2;
	}

	.input-info-list {
		width: @iw;

		li {
			position: relative;
			margin-bottom: calc(@w * 0.07);
			width: @iw;
			font-size: @fs;

			.info-input {
				--baseInputWidth: @iw;
				--baseInputHeight: calc(@fs * 2);
				--baseInputFontsize: @ifs;
				--passwordInputWidth: @iw;
				--passwordInputHeight: calc(@fs * 2);
				--passwordInputFontsize: @ifs;
			}

			.signal {
				position: absolute;
				left: 105%;
				top: 0;
				text-align: center;
				font-size: calc(@fs * 1.3);
				color: var(--red);
			}

			.sig-message {
				margin-top: calc(@fs * 0.4);
				line-height: @fs;
				margin-bottom: calc(-0.7 * @fs);
				padding: 0 calc(@fs / 2);
				text-align: left;
				font-size: calc(@fs * 0.2);
				color: var(--red);
			}
		}
	}

	.verification {
		margin-bottom: @fs;
		width: @iw;
		height: calc(@fs * 2);
		display: flex;
		justify-content: space-between;
		align-items: center;

		.veri-input {
			--baseInputWidth: calc(@iw / 2);
			--baseInputHeight: calc(@fs * 2);
			--baseInputFontsize: @ifs;
		}

		img {
			width: 40%;
			height: 100%;
		}
	}

	.regis-button {
		width: @iw;
		line-height: 2;
		font-size: calc(@fs * 1.2);
    color: white;
    font-weight: bold;
		border-radius: 1.5vw;
		background-image: linear-gradient(-200deg, #fac0e7, #91baff);
	}

	.register-entry {
		margin: calc(@fs * 0.5) 0;
		font-size: calc(@fs * 0.5);

		span {
			color: var(--blue);

			&:hover {
				cursor: pointer;
			}
		}
	}
}
</style>